﻿using Blm.RabbitMQ.MessageQueue;
using Blm.RabbitMQ.Models;
using Blm.Utils.Extensions;
using Meta.RabbitMQ.Generic;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using System;
using System.Threading.Tasks;
using VisionCloud.Domain.DtoModel.RabbitMq;
using VisionCloud.Domain.Repository.Interface.Ms;
using VisionCloud.Domain.UnitOfWork;
using VisionCloud.Service.Fms;
using VisionCloud.Utility;

namespace VisionCloud.Web.Service.MQListener
{
    public class ProjectAddBackgroundService : BlmRabbitMQStorageSubscriberBase<ProjectAddDto>
    {
        private readonly ILogger<ProjectAddBackgroundService> logger;
        private readonly ProjectDCService dcService;
        private readonly IUnitOfWork unitOfWork;
        private readonly IMsProjectRepository msProjectRepository;

        public ProjectAddBackgroundService(IServiceProvider serviceProvider,
            ILogger<ProjectAddBackgroundService> logger,
            ProjectDCService dcService,
            IUnitOfWork unitOfWork,
            IMsProjectRepository msProjectRepository) : base(serviceProvider)
        {
            this.logger = logger;
            this.dcService = dcService;
            this.unitOfWork = unitOfWork;
            this.msProjectRepository = msProjectRepository;
        }

        public override StorageWayEm StorageWay => StorageWayEm.OnlyStorage;

        public override ClientOption ClientOption => new ClientOption("visioncloud_project_add_exchange", "visioncloud_routingkey", ExchangeType.Topic, "visioncloud_project_add_queue", RabbitMQConnectPoolName.CloudServerHost);

        public override async Task InvokeAsync(ProjectAddDto model)
        {
            try
            {
                if (model == null)
                    throw new ArgumentNullException("反序列化ProjectIdAddDto失败");

                var project = await msProjectRepository.GetByIdAsync(model.ProjectId);

                #region 获取项目经纬度坐标，Added at 20230207

                var address = project.Province + project.City + project.Town + project.Address;
                (float lat, float lng) = await AddressHelper.GetLocationFromAddress(address);
                project.Latitude = lat != float.NaN ? lat : 0;
                project.Longitude = lng != float.NaN ? lng : 0;

                #endregion 获取项目经纬度坐标，Added at 20230207

                var mapProjectId = await dcService.AddProject(project);
                project.MapProjectId = mapProjectId;
                msProjectRepository.Update(project);
                await unitOfWork.SaveChangesAsync();
            }
            catch (Exception ex)
            {
                logger.LogError($"ProjectAddBackgroundService报错：{ex.Message}，{ex.StackTrace}，队列内容：{model?.ToJsonStr()}", ex);
            }
        }
    }
}
